﻿using MSScriptControl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using WindowsFormsApplication2;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        CookieCollection cklist = new CookieCollection();
        List<GanjiImage> SendPicResult = new List<GanjiImage>();

        string userid;
        public List<string> picFileList = new List<string>();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //string s = Properties.Settings.Default.ck.ToString();
            //string gjss = @"https://passport.ganji.com/ajax.php?dir=captcha&module=login_captcha&nocache=1446526061";
            //string picout = doreqoutget(false, gjss, "");
            //string gj1u = "https://passport.ganji.com/login.php?next=/";
            //string aou = doreqoutget(false, gj1u, "");
            //string hspt = "window.PAGE_CONFIG.__hash__ = '([^\"]+)';";
            //string hsout = getBysrcAndpattern(aou, hspt);

            //ScriptControlClass js = new ScriptControlClass();
            //js.Language = "javascript";
            //var at = Math.Round(decimal.Parse(js.Eval(" new Date().getTime();").ToString()), 0);
            //string loggj = @"https://passport.ganji.com/login.php?callback=jQuery18204047201075591147_" + ((long)at - new Random().Next(2000000, 3000000)).ToString() + "&username=elingsoft123&password=wcb110120&checkCode=&setcookie=14&second=&parentfunc=&redirect_in_iframe=&next=%2F&__hash__=" + hsout + "&_=" + at;

            //string loggjurl = @"https://passport.ganji.com/login.php";
            //string postdata = "callback=jQuery18204047201075591147_" + ((long)at - new Random().Next(2000000, 3000000)).ToString() + "&username=elingsoft123&password=wcb110120&checkCode=&setcookie=14&second=&parentfunc=&redirect_in_iframe=&next=%2F&__hash__=" + hsout + "&_=" + at;
            ////string myou = doreqout(false, loggjurl, postdata);
            //string myou = doreqoutget(false, loggj, "");
            //string mypo = "http://www.ganji.com/vip/my_post_list.php";
            //string poout = doreqoutget(true, mypo, "");
            //var a = 0;


            my58Login login = new my58Login(cklist);

            login.StartLogin(textBox2.Text, textBox3.Text);
            userid = getBysrcAndpattern(cklist["www58com"].Value.ToString(), "UserID=(\\d+)&");
            label2.Text = cklist.Count.ToString();
            if (cklist.Count > 5)
            {
                label4.Text = login.LastStatus;
                richTextBox2.Text = listallcookies(cklist);
            }
            else
            {

                label4.Text = login.LastStatus;
                richTextBox2.Text = listallcookies(cklist);

            }
            string mypo = "http://my.58.com/";
            string poout = doreqoutget(true, mypo, "");

            richTextBox1.Text = poout;
        }


        private static string getBysrcAndpattern(string msg, string pt)
        {


            var match2 = Regex.Match(msg, pt);
            string rich2 = match2.Groups[1].Value;
            return rich2;
        }
        public string doreqoutget(bool allowdir, string urla, string postdata)
        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urla);

            req.CookieContainer = new CookieContainer();


            req.CookieContainer.Add(cklist);
            //WebProxy wp = new WebProxy("121.40.195.200:808");

            //req.Proxy = wp;
            req.Method = "GET";

            req.AllowAutoRedirect = allowdir;

            if (!string.IsNullOrEmpty(postdata))
            {

                byte[] bs = Encoding.ASCII.GetBytes(postdata);
                string responseData = String.Empty;

                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = bs.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                    reqStream.Close();
                }
            }
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            //    WebHeaderCollection responseHeaders = res.Headers;

            //if (keepContext)
            //{
            //    context.Cookies = res.Cookies;
            //    context.Referer = _requestUrl;
            //}
            using (Stream stream = res.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    string msg = streamReader.ReadToEnd();

                    int a = res.Cookies.Count;
                    if (a > 0)
                    {


                        cklist.Add(res.Cookies);
                    }
                    //    string lc = res.Headers["Location"].ToString();
                    return msg;
                }
            }

            return "";

        }


        public string doreqout(bool allowdir, string urla, string postdata)
        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urla);

            req.CookieContainer = new CookieContainer();


            req.CookieContainer.Add(cklist);

            req.Method = "POST";
            WebProxy wp = new WebProxy("121.40.195.200:808");

            // req.Proxy = wp;
            req.AllowAutoRedirect = allowdir;
            byte[] bs = Encoding.ASCII.GetBytes(postdata);
            string responseData = String.Empty;
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = bs.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            using (Stream stream = res.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    string msg = streamReader.ReadToEnd();

                    int a = res.Cookies.Count;
                    if (a > 0)
                    {


                        cklist.Add(res.Cookies);
                    }
                    //    string lc = res.Headers["Location"].ToString();
                    return msg;
                }
            }

            return "";

        }
        public string doreqoutPub(bool allowdir, string urla, string postdata)
        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urla);

            req.CookieContainer = new CookieContainer();


            req.CookieContainer.Add(cklist);
            req.Headers.Add("Upgrade-Insecure-Requests", "1");
            req.Referer = "http://www.ganji.com/pub/pub.php?act=pub&method=load&cid=7&mcid=20&domain=nb";
            req.Method = "POST";
            WebProxy wp = new WebProxy("121.40.195.200:808");

            // req.Proxy = wp;
            req.AllowAutoRedirect = allowdir;

            string responseData = String.Empty;
            req.Method = "POST";
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            var boundarytx = DateTime.Now.Ticks.ToString("x");
            string pt = "Content-Disposition: form-data; name=\"([^\"]+)\"\\s*(\\S*)\\s*------";
            MatchCollection match2 = Regex.Matches(postdata, pt);
            string postbody = "";
            foreach (Match item in match2)
            {
                string rich1 = item.Groups[1].Value;
                string rich2 = item.Groups[2].Value;
                // richTextBox1.Text += rich1 + "," + rich2 + ",";

                var vbody = string.Format(@"------WebKitFormBoundary" + boundarytx + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n\r\n", rich1, rich2);
                postbody += vbody;
            }
            postbody += @"------WebKitFormBoundary" + boundarytx + "--";

            Encoding e8859Encode = Encoding.GetEncoding("iso-8859-1");
            //  byte[] bs = Encoding.ASCII.GetBytes(postbody);
            byte[] bs = Encoding.UTF8.GetBytes(postbody);
            // byte[] bs = e8859Encode.GetBytes(postbody); 
            req.ContentType = "multipart/form-data; boundary=----WebKitFormBoundary" + boundarytx;
            req.ContentLength = bs.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            using (Stream stream = res.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    string msg = streamReader.ReadToEnd();

                    int a = res.Cookies.Count;
                    if (a > 0)
                    {


                        cklist.Add(res.Cookies);
                    }
                    //    string lc = res.Headers["Location"].ToString();
                    return msg;
                }
            }

            return "";

        }
        public string doreqoutPub2(bool allowdir, string urla, string postdata)
        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urla);

            req.CookieContainer = new CookieContainer();
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Win64; x64; Trident/7.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0E; .NET4.0C; Tablet PC 2.0; InfoPath.3)";

            //11.11 
            req.CookieContainer.Add(cklist);
            req.Headers.Add("Upgrade-Insecure-Requests", "1");
            req.Referer = "http://www.ganji.com/pub/pub.php?act=pub&method=load&cid=7&mcid=20&domain=nb";
            req.Method = "POST";
            WebProxy wp = new WebProxy("121.40.195.200:808");

            // req.Proxy = wp;
            req.AllowAutoRedirect = allowdir;

            string responseData = String.Empty;
            req.Method = "POST";
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            var boundarytx = DateTime.Now.Ticks.ToString("x");
            //  string pt = "multipart/form-data; boundary=---------------------------7dfc8820c4c";
            string pt = "multipart/form-data; boundary=---------------------------" + boundarytx;
            postdata = Properties.Settings.Default.postnr.ToString();
            string ptmatch = "Content-Disposition: form-data; name=\"([^\"]+)\"\\s*(\\S*)\\s*------";
            MatchCollection match2 = Regex.Matches(postdata, ptmatch);
            string postbody = "\r\n\r\n";
            foreach (Match item in match2)
            {
                string rich1 = item.Groups[1].Value;
                string rich2 = item.Groups[2].Value;
                // richTextBox1.Text += rich1 + "," + rich2 + ",";

                var vbody = string.Format(@"-----------------------------" + boundarytx + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", rich1, rich2);
                postbody += vbody;
            }
            postbody += @"-----------------------------" + boundarytx + "--";

            //    Encoding e8859Encode = Encoding.GetEncoding("iso-8859-1");
            //  byte[] bs = Encoding.ASCII.GetBytes(postbody);
            //  postbody = Properties.Settings.Default.posthct;


            byte[] bs = Encoding.UTF8.GetBytes(postbody);
            // byte[] bs = e8859Encode.GetBytes(postbody); 
            req.ContentType = pt;
            req.ContentLength = bs.Length;
            req.Accept = "gzip, deflate";
            // req.CookieContainer = new System.Net.CookieContainer();
            //   req.CookieContainer.Add( strCokAddColnew("lg=1; ganji_uuid=8295570832976495518323; ganji_xuuid=8c2c4ca2-2758-42a0-90b1-037bf7bd2621.1441182165740; __utma=32156897.89665725.1446446419.1446446419.1446685942.2; __utmz=32156897.1446446419.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); undefined=0b599f13-59bb-4046-a877-352f7c5bc2c5; citydomain=nb; NTKF_T2D_CLIENTID=guest016AF395-C541-D138-A824-C6F7D48CE723; sscode=6YJzZSDvFyZ0a0Uw6YSYtzmR; GanjiUserName=elingsoft123; GanjiUserInfo=%7B%22user_id%22%3A568760582%2C%22email%22%3A%22%22%2C%22username%22%3A%22elingsoft123%22%2C%22user_name%22%3A%22elingsoft123%22%2C%22nickname%22%3A%22%22%7D; bizs=%5B%5D; supercookie=AGL4AmLjAGtlWQyvMQL5BGV4MzZ2LJAwBQAzZQZlMwyvBTZlMQyyMJSzMGV3BTMvZTL%3D; __utmb=32156897.10.10.1446685942; __utmt=1; 58uuid=d60ba0ca-88f0-4122-bbf5-a6cda97fde62; last_name=elingsoft123; _gl_tracker=%7B%22ca_source%22%3A%22-%22%2C%22ca_name%22%3A%22-%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_id%22%3A%22-%22%2C%22ca_s%22%3A%22self%22%2C%22ca_n%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22sid%22%3A33801389483%7D; __utmc=32156897; GANJISESSID=ac5c6e3d6fe1e048616e1913f6266fa9",".ganji.com",new CookieCollection()));
            //11.11
            // req.CookieContainer.Add(strCokAddColnew("lg=1;ganji_uuid=5170713550418216074941; ganji_xuuid=a00bd1e8-8802-4d0f-8737-20af1e6f4f17; undefined=51fcc4f3-d030-4435-85e1-171248097f40; supercookie=AGL4AmLjAGtlWQyvMQL5BGV4MzZ2LJAwBQAzZQZlMwyvBTZlMQyyMJSzMGV3BTMvZTL%3D; bdshare_firstime=1446620003045; 58uuid=a8a7d56c-88fd-46a0-872a-85a370f9b007; GANJISESSID=826e55f6ec397d421876d60eddeb9b76; sscode=ok%2FU3YcPpemPfJQPokXROutr; GanjiUserName=elingsoft123; GanjiUserInfo=%7B%22user_id%22%3A568760582%2C%22email%22%3A%22%22%2C%22username%22%3A%22elingsoft123%22%2C%22user_name%22%3A%22elingsoft123%22%2C%22nickname%22%3A%22%22%7D; bizs=%5B%5D; last_name=elingsoft123; STA_DS=1; nTalk_CACHE_DATA={uid:kf_10111_ISME9754_568760582}; NTKF_T2D_CLIENTID=guestA308F3D1-01E9-9234-6C4A-D489AC18228C; lg=1; citydomain=nb; __utma=32156897.1762231046.1444439497.1447203159.1447212544.14; __utmc=32156897; __utmz=32156897.1447212544.14.8.utmcsr=ganji.com|utmccn=(referral)|utmcmd=referral|utmcct=/vip/my_post_list.php; _gl_tracker=%7B%22ca_source%22%3A%22-%22%2C%22ca_name%22%3A%22-%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_id%22%3A%22-%22%2C%22ca_s%22%3A%22self%22%2C%22ca_n%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22sid%22%3A31958504601%7D", ".ganji.com", new CookieCollection()));

            //////////////////////////////////////////////////////////////////////////
            //  req.CookieContainer.Add(strCokAddColnew("lg=1;ganji_uuid=8295570832976495518323; ganji_xuuid=8c2c4ca2-2758-42a0-90b1-037bf7bd2621.1441182165740; citydomain=nb;  sscode=6YJzZSDvFyZ0a0Uw6YSYtzmR; GanjiUserName=elingsoft123; GanjiUserInfo=%7B%22user_id%22%3A568760582%2C%22email%22%3A%22%22%2C%22username%22%3A%22elingsoft123%22%2C%22user_name%22%3A%22elingsoft123%22%2C%22nickname%22%3A%22%22%7D; bizs=%5B%5D; supercookie=AGL4AmLjAGtlWQyvMQL5BGV4MzZ2LJAwBQAzZQZlMwyvBTZlMQyyMJSzMGV3BTMvZTL%3D;  last_name=elingsoft123", ".ganji.com", new CookieCollection()));
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            using (Stream stream = res.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    string msg = streamReader.ReadToEnd();
                    if (string.IsNullOrEmpty(msg))
                    {
                        label4.Text = "发布成功";
                        richTextBox2.Text += res.Headers["Location"].ToString();
                    }
                    int a = res.Cookies.Count;
                    if (a > 0)
                    {


                        cklist.Add(res.Cookies);
                    }
                    //    string lc = res.Headers["Location"].ToString();
                    return msg;
                }
            }

            return "";

        }
        private void button2_Click(object sender, EventArgs e)
        {
            //ScriptControlClass js = new ScriptControlClass();
            //js.Language = "javascript";
            //var a = Math.Round(decimal.Parse(js.Eval(" new Date().getTime();").ToString()), 0);
            //string s = richTextBox2.Text;
            //string pt = "Content-Disposition: form-data; name=\"([^\"]+)\"\\s*(\\S*)\\s*------";
            //MatchCollection match2 = Regex.Matches(s, pt);
            //foreach (Match item in match2)
            //{
            //    string rich1 = item.Groups[1].Value;
            //    string rich2 = item.Groups[2].Value;
            //    richTextBox1.Text += rich1 + "," + rich2 + ",";
            //}
            GanjiHousePub hp = new GanjiHousePub(cklist);
            hp.InitCookie();





            hp.xiaoqu = "水岸枫情";


            hp.xiaoqu_pinyin = "shuianfengqing1";

            hp._unused_district_id = "鄞州";

            hp.district_id = "2054";


            hp._unused_street_id = "石碶";


            hp.street_id = "3612";



            hp.xiaoqu_address = "联丰薛家南路";


            hp.latlng = "b121.508273,29.867328";


            hp.area = "99";



            hp.ceng = "1";


            hp.ceng_total = "11";

            hp._unused_chaoxiang = "南";

            hp.chaoxiang = "2";


            hp._unused_zhuangxiu = "精装修";

            hp.zhuangxiu = "2";


            hp._unused_fang_xing = "普通住宅";


            hp.fang_xing = "3";


            //  hp.peizhi = "chuang";


            hp.price = "111";


            //  hp._unused_pay_type_int = "押一付三";

            //  hp.pay_type_int = "1";


            hp.title = "水岸枫情新出售111w";


            hp.description = "水岸枫情新出售111w水岸枫情新出售111w";
            hp.person = "王成";
            hp.phone = "15957899033";

            hp._unused_bid_structure = "高层板楼";
            hp.bid_structure = "2";

            hp._unused_house_property = "商品房";

            hp.house_property = "1";

            hp._unused_land_tenure = "70年";
            hp.land_tenure = "1";
            hp.niandai = "1999";


            StringBuilder sb = new StringBuilder("[[");
            foreach (GanjiImage mi in SendPicResult)
            {
                sb.Append("{\"image\":\"" + mi.image + "\",\"thumb_image\":\"" + mi.thumb_image + "\",\"width\":" + mi.width + ",\"height\":" + mi.height + ",\"id\":\"" + mi.id + "\",\"is_new\":" + mi.is_new.ToString().ToLower() + "},");

            }
            if (sb.ToString().IndexOf('|') > 0)
            {
                sb.Remove(sb.ToString().LastIndexOf(','), 1);
            }
            sb.Append("],[]]");
            hp.images = sb.ToString();
            string pudaddr = "http://www.ganji.com/pub/pub.php?cid=7&mcid=21&act=pub&method=submit";

            string czout = hp.doreqoutPub1(false, pudaddr, "");

            label4.Text = hp.LastStatus;
            richTextBox2.Text += czout;
            int b = 0;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            cklist = new CookieCollection();
            //string c = File.ReadAllText(Application.StartupPath+"\\"+"gjc.js");
            ////ScriptControlClass js = new ScriptControlClass();
            ////js.Language = "javascript";
            ////var a = js.Eval("var w=10;var t=2; p=w/t;");  

            //string o = "b()";
            ////  string o="aaa('qqq')";
            //string auuid = ExecuteScript(o, c);


            //Cookie ck = new Cookie();
            //ck.Name = "ganji_uuid";
            //ck.Value = auuid;
            //ck.Path = "/";
            //ck.Domain = ".ganji.com";
            //cklist.Add(ck);
            //string gjss = @"https://passport.ganji.com/ajax.php?dir=captcha&module=login_captcha&nocache=1446526051";
            //Image im = GetImgFromUrl(gjss);
            textBox1.Text = "";
            GanjiLogin Clogin = new GanjiLogin(cklist);
            pictureBox1.Image = Clogin.StartLogin();
            label2.Text = cklist.Count.ToString();
            label4.Text = Clogin.LastStatus;

        }
        public Image GetImgFromUrl(string url)
        {
            WebRequest webRequest = WebRequest.Create(url);
            HttpWebRequest request = webRequest as HttpWebRequest;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string mheader = response.Headers["Set-Cookie"].ToString();



            System.Collections.Hashtable hs = new System.Collections.Hashtable();

            string sa = mheader.Split(';')[0];






            Cookie c = new Cookie();
            c.Name = Regex.Replace(sa.Substring(0, sa.IndexOf('=')), @"\r\n", "").ToString();
            c.Value = Regex.Replace(sa.Substring(sa.IndexOf('=') + 1), @"\r\n", "").ToString();

            c.Domain = ".ganji.com";

            CookieCollection ckl = strCokAddCol1(mheader, "58.com");
            //    WebHeaderCollection responseHeaders = res.Headers;

            //if (keepContext)
            //{
            //    context.Cookies = res.Cookies;
            //    context.Referer = _requestUrl;
            //}
            cklist.Add(c);
            Stream stream = response.GetResponseStream();
            stream.ReadTimeout = 1000;
            Image image = Image.FromStream(stream);

            stream.Close();
            response.Close();
            return image;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //string checkCode = textBox1.Text;

            //string gj1u = "https://passport.ganji.com/login.php?next=/";
            //string aou = doreqoutget(false, gj1u, "");
            //string hspt = "window.PAGE_CONFIG.__hash__ = '([^\"]+)';";
            //string hsout = getBysrcAndpattern(aou, hspt);

            //ScriptControlClass js = new ScriptControlClass();
            //js.Language = "javascript";
            //var at = Math.Round(decimal.Parse(js.Eval(" new Date().getTime();").ToString()), 0);
            //string loggj = @"https://passport.ganji.com/login.php?callback=jQuery18204047201075591147_" + ((long)at - new Random().Next(2000000, 3000000)).ToString() + "&username=elingsoft123&password=wcb110120&checkCode=" + checkCode + "&setcookie=14&second=&parentfunc=&redirect_in_iframe=&next=%2F&__hash__=" + hsout + "&_=" + at;

            //string loggjurl = @"https://passport.ganji.com/login.php";
            //string postdata = "callback=jQuery18204047201075591147_" + ((long)at - new Random().Next(2000000, 3000000)).ToString() + "&username=elingsoft123&password=wcb110120&checkCode=" + checkCode + "&setcookie=14&second=&parentfunc=&redirect_in_iframe=&next=%2F&__hash__=" + hsout + "&_=" + at;
            ////string myou = doreqout(false, loggjurl, postdata);
            //string myou = doreqoutget(false, loggj, "");
            //

            GanjiLogin Clogin = new GanjiLogin(cklist);
            Clogin.validationLogin(textBox1.Text, textBox2.Text, textBox3.Text);
            label2.Text = cklist.Count.ToString();
            if (cklist.Count > 5)
            {
                label4.Text = Clogin.LastStatus;
                richTextBox2.Text = listallcookies(cklist);
            }
            else
            {

                label4.Text = Clogin.LastStatus;
                richTextBox2.Text = listallcookies(cklist);

            }
            string mypo = "http://www.ganji.com/vip/my_post_list.php";
            string poout = doreqoutget(true, mypo, "");

            richTextBox1.Text = poout;
            var a = 0;
        }

        public string listallcookies(CookieCollection ckl)
        {

            string s = "";
            foreach (Cookie c in ckl)
            {
                s += c.Name + "=" + System.Web.HttpUtility.UrlDecode(c.Value) + ",";
            }
            return s;
        }
        public static CookieCollection strCokAddCol1(string s, string defaultDomain)
        {
            CookieCollection cc = new CookieCollection();
            if (string.IsNullOrEmpty(s) || s.Length < 5 || s.IndexOf("=") < 0) return cc;
            if (string.IsNullOrEmpty(defaultDomain) || defaultDomain.Length < 5) return cc;
            s.TrimEnd(new char[] { ';' }).Trim();

            //用软件截取的cookie会带有expires，要把它替换掉【isGood代码】
            if (s.IndexOf("expires=") >= 0)
            {
                s = replace(s, @"expires=[\w\s,-:]*GMT[;]?", "");
            }
            //只有一个cookie直接添加【isGood代码】
            if (s.IndexOf(";") < 0)
            {
                System.Net.Cookie c = new System.Net.Cookie(s.Substring(0, s.IndexOf("=")), s.Substring(s.IndexOf("=") + 1));
                c.Domain = defaultDomain;
                cc.Add(c);
                return cc;
            }
            //不同站点与不同路径一般是以英文道号分别【isGood代码】
            if (s.IndexOf(",") > 0)
            {
                s.TrimEnd(new char[] { ',' }).Trim();
                foreach (string s2 in s.Split(','))
                {
                    cc = strCokAddCol(s2, defaultDomain, cc);
                }
                return cc;
            }
            return cc;
        }

        private static CookieCollection strCokAddCol(string s, string defaultDomain, CookieCollection cc)
        {
            try
            {
                s.TrimEnd(new char[] { ';' }).Trim();
                System.Collections.Hashtable hs = new System.Collections.Hashtable();

                string sa = s.Split(';')[0];






                Cookie c = new Cookie();
                c.Name = Regex.Replace(sa.Substring(0, sa.IndexOf('=')), @"\r\n", "").ToString();
                c.Value = Regex.Replace(sa.Substring(sa.IndexOf('=') + 1), @"\r\n", "").ToString();

                c.Domain = defaultDomain;
                cc.Add(c);

            }
            catch (Exception e)
            {

            }
            return cc;
        }
        private static CookieCollection strCokAddColnew(string s, string defaultDomain, CookieCollection cc)
        {
            try
            {
                s.TrimEnd(new char[] { ';' }).Trim();
                System.Collections.Hashtable hs = new System.Collections.Hashtable();





                foreach (string sa in s.Split(';'))
                {




                    Cookie c = new Cookie();
                    c.Name = Regex.Replace(sa.Trim().Substring(0, sa.Trim().IndexOf('=')), @"\r\n", "").ToString();
                    c.Value = Regex.Replace(sa.Trim().Substring(sa.Trim().IndexOf('=') + 1), @"\r\n", "").ToString();

                    c.Domain = defaultDomain;
                    cc.Add(c);
                }
            }
            catch (Exception e)
            {
                int a = 0;
            }
            return cc;
        }


        /// <summary>
        /// 替换字符【isGood代码】
        /// </summary>
        /// <param name="strSource">来源</param>
        /// <param name="strRegex">表达式</param>
        /// <param name="strReplace">取代</param>
        public static string replace(string strSource, string strRegex, string strReplace)
        {
            try
            {
                Regex r;
                r = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                string s = r.Replace(strSource, strReplace);
                return s;
            }
            catch
            {
                return strSource;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //string pudaddr = "http://www.ganji.com/pub/pub.php?cid=7&mcid=20&act=pub&method=submit";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                picFileList.Add(openFileDialog1.FileName);
            }//string fydata = Properties.Settings.Default.postnr.ToString();

            picct.Text = picFileList.Count.ToString();
            //Cookie ck = new Cookie();
            //ck.Name = "citydomain";
            //ck.Value = "nb";
            //ck.Path = "/";
            //ck.Domain = ".ganji.com";
            //cklist.Add(ck);
            //string pubout = doreqoutPub(false, pudaddr, fydata);
            //var a = 0;

        }

        private void button6_Click(object sender, EventArgs e)
        {
            GanjiHousePub hp = new GanjiHousePub(cklist);
            hp.InitCookie();





            hp.xiaoqu = "水岸枫情";


            hp.xiaoqu_pinyin = "shuianfengqing1";

            hp._unused_district_id = "鄞州";

            hp.district_id = "2054";


            hp._unused_street_id = "石碶";


            hp.street_id = "3612";



            hp.xiaoqu_address = "联丰薛家南路";


            hp.latlng = "b121.508273,29.867328";


            hp.area = "99";



            hp.ceng = "1";


            hp.ceng_total = "11";

            hp._unused_chaoxiang = "南";

            hp.chaoxiang = "2";


            hp._unused_zhuangxiu = "精装修";

            hp.zhuangxiu = "2";


            hp._unused_fang_xing = "普通住宅";


            hp.fang_xing = "3";


            hp.peizhi = "chuang";


            hp.price = "1111";


            hp._unused_pay_type_int = "押一付三";

            hp.pay_type_int = "1";


            hp.title = "水岸枫情新出租111";


            hp.description = "水岸枫情新出租111水岸枫情新出租111";

            hp.phone = "15957899033";
            StringBuilder sb = new StringBuilder("[[");
            foreach (GanjiImage mi in SendPicResult)
            {
                sb.Append("{\"image\":\"" + mi.image + "\",\"thumb_image\":\"" + mi.thumb_image + "\",\"width\":" + mi.width + ",\"height\":" + mi.height + ",\"id\":\"" + mi.id + "\",\"is_new\":" + mi.is_new.ToString().ToLower() + "},");

            }
            if (sb.ToString().IndexOf('|') > 0)
            {
                sb.Remove(sb.ToString().LastIndexOf(','), 1);
            }
            sb.Append("],[]]");
            hp.images = sb.ToString();
            string pudaddr = "http://www.ganji.com/pub/pub.php?cid=7&mcid=20&act=pub&method=submit";

            string czout = hp.doreqoutPub2(false, pudaddr, "");

            label4.Text = hp.LastStatus;
            richTextBox2.Text += czout;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            List<Cookie> ckls = new List<Cookie>();
            foreach (Cookie cka in cklist)
            {

                if (cka.Name.Trim().ToLower() != "loginact")
                {
                    ckls.Add(cka);
                }
            }
            cklist = new CookieCollection();
            foreach (Cookie item in ckls)
            {
                cklist.Add(item);
            }
            string pg1 = "http://www.ganji.com/common/pub.php?category=housing&type=1&_pdt=fang";
            string pubpageout1 = doreqoutget(false, pg1, "");
            string pubpage = "http://www.ganji.com/pub/pub.php?act=pub&method=load&cid=7&mcid=20&domain=nb&_pdt=fang";
            string pubpageout = doreqoutget(false, pubpage, "");
            string pudaddr = "http://www.ganji.com/pub/pub.php?cid=7&mcid=20&act=pub&method=submit";

            string fydata = Properties.Settings.Default.postnr.ToString();


            Cookie ck = new Cookie();
            ck.Name = "citydomain";
            ck.Value = "nb";
            ck.Path = "/";
            ck.Domain = ".ganji.com";
            cklist.Add(ck);
            ck = new Cookie();
            ck.Name = "lg";
            ck.Value = "1";
            ck.Path = "/";
            ck.Domain = ".ganji.com";
            cklist.Add(ck);
            string pubout = doreqoutPub2(false, pudaddr, fydata);
            var a = 0;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            string c = File.ReadAllText(Application.StartupPath + "\\" + "gjgc.js");
            //ScriptControlClass js = new ScriptControlClass();
            //js.Language = "javascript";
            //var a = js.Eval("var w=10;var t=2; p=w/t;");  

            string o = "guid()";
            //  string o="aaa('qqq')";
            string a = ExecuteScript(o, c);



            int ab = 0;
        }

        private string ExecuteScript(string sExpression, string sCode)
        {
            MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl();
            scriptControl.UseSafeSubset = false;
            scriptControl.AllowUI = true;

            scriptControl.Language = "JScript";

            scriptControl.AddCode(sCode);
            try
            {
                string str = scriptControl.Eval(sExpression).ToString();
                return str;
            }
            catch (Exception ex)
            {
                string str = ex.Message;
            }
            return null;
        }

        private void button9_Click(object sender, EventArgs e)
        {
            //{
            //    List<Cookie> ckls = new List<Cookie>();
            //    foreach (Cookie cka in cklist)
            //    {

            //        if (cka.Name.Trim().ToLower() != "loginact")
            //        {
            //            ckls.Add(cka);
            //        }
            //    }
            //    cklist = new CookieCollection();
            //    foreach (Cookie item in ckls)
            //    {
            //        cklist.Add(item);
            //    }
            //    string pg1 = "http://www.ganji.com/common/pub.php?category=housing&type=1&_pdt=fang";
            //    string pubpageout1 = doreqoutget(false, pg1, "");
            //    string pubpage = "http://www.ganji.com/pub/pub.php?act=pub&method=load&cid=7&mcid=20&domain=nb&_pdt=fang";
            //    string pubpageout = doreqoutget(false, pubpage, "");
            //    string pudaddr = "http://www.ganji.com/pub/pub.php?cid=7&mcid=20&act=pub&method=submit";

            //    string fydata = Properties.Settings.Default.postnr.ToString();

            //FileStream files = new FileStream("C:\\Users\\Public\\Pictures\\Sample Picture\\s.jpg", FileMode.Open);
            //byte[] imgByte = new byte[files.Length];
            //files.Read(imgByte, 0, imgByte.Length);
            //files.Close();
            //Cookie ck = new Cookie();
            //ck.Name = "citydomain";
            //ck.Value = "nb";
            //ck.Path = "/";
            //ck.Domain = ".ganji.com";
            //cklist.Add(ck);
            //ck = new Cookie();
            //ck.Name = "lg";
            //ck.Value = "1";
            //ck.Path = "/";
            //ck.Domain = ".ganji.com";
            //cklist.Add(ck);
            // string pubout = doreqoutPub2(false, pudaddr, fydata);

            string c = File.ReadAllText(Application.StartupPath + "\\" + "gjgc.js");
            //ScriptControlClass js = new ScriptControlClass();
            //js.Language = "javascript";
            //var a = js.Eval("var w=10;var t=2; p=w/t;");  

            string oid = "guid()";
            //  string o="aaa('qqq')";
            //string aid = ExecuteScript(oid, c);


            int i = 1;
            if (picFileList.Count > 0)
            {

                foreach (string s in picFileList)
                {
                    i++;
                    GanjiPic GJpic = new GanjiPic(cklist);
                    GJpic.InitCookie();
                    //  GJpic.FilePathStr = "C:\\123\\c.jpg";

                    GJpic.FilePathStr = s;
                    GJpic.uploadDir = "housing";
                    GJpic.resizeWidth = "600";
                    GJpic.resizeHeight = "450";
                    GJpic.guid = GJpic.ExeJavascript(Application.StartupPath + "\\" + "gjgc.js", oid).Replace("guid_1", "guid_" + i);
                    //  GJpic.guid = "guid_1_14472904817060_3982545433100313";

                    string spicout = GJpic.DoRequestPost(true, "http://image.ganji.com/upload.php", "");

                    getPicResource(SendPicResult, spicout, "url\":\"([^\"]+)\",\"thumbUrl\":\"([^\"]+)\"", GJpic.guid);
                    richTextBox2.Text += spicout;
                    label2.Text = cklist.Count.ToString();
                    if (cklist.Count > 5)
                    {
                        label4.Text = GJpic.LastStatus;
                        //  richTextBox2.Text = listallcookies(cklist);
                    }
                    picct.Text = (picFileList.Count - i).ToString();
                }
                picFileList.Clear();
                picct.Text = picFileList.Count.ToString();
                var a = 0;
            }
        }

        public void getPicResource(List<GanjiImage> SendPicResult, string msg, string pt, string guid)
        {

            var match2 = Regex.Match(msg, pt);
            SendPicResult.Add(new GanjiImage() { image = match2.Groups[1].Value.Replace("\\", ""), thumb_image = match2.Groups[2].Value.Replace("\\", ""), height = "600", width = "450", id = guid, is_new = true });

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button10_Click(object sender, EventArgs e)
        {
            int i = 1;
            if (picFileList.Count > 0)
            {

                foreach (string s in picFileList)
                {
                    i++;
                    my58Pic mypic = new my58Pic(cklist);
                    mypic.username = textBox2.Text;
                    mypic.fileToUpload = s;
                    string spicout = mypic.DoRequestPost();

                    richTextBox2.Text += spicout + "****" + (i - 1);
                    label2.Text = cklist.Count.ToString();
                    if (cklist.Count > 5)
                    {
                        label4.Text = mypic.LastStatus;
                        //  richTextBox2.Text = listallcookies(cklist);
                    }
                    picct.Text = (picFileList.Count - i).ToString();

                    SendPicResult.Add(new GanjiImage() { image = spicout });
                }
                picFileList.Clear();
                picct.Text = picFileList.Count.ToString();
                var a = 0;
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            ScriptControlClass js = new ScriptControlClass();
            js.Language = "javascript";
            var a1 = js.Eval(" (new Date().getTime() *10).toFixed(0)");
            string a2 = new Random().Next(10316818, 99316818).ToString() + new Random().Next(83893907,83893907).ToString();

            my58HousePub myPub = new my58HousePub(cklist);
            myPub.GTID=a1.ToString()+"."+a2;
            myPub.doreqoutget(true, "http://post.58.com/135?PGTID=" + myPub.GTID + "&ClickID=6", "");
            myPub.xiaoqu = "338043";
            myPub.xiaoquname = "水岸枫情";
            myPub.localArea = "141";
            myPub.localDiduan = "4900";
            myPub.dizhi = "联丰薛家南路";
            myPub.area = "111";
            myPub.Floor = "1";
            myPub.zonglouceng = "11";
            myPub.MinPrice = "1111";
            myPub.Title = "水岸风情1111出租精装修出租";
            myPub.Content = "水岸风情1111出租精装修出租水岸风情1111出租精装修出租水岸风情1111出租精装修出租水岸风情1111出租精装修出租水岸风情1111出租精装修出租";
            myPub.goblianxiren = "王成";
            myPub.Phone = "15957899036";
            myPub.userid = this.userid;

            StringBuilder sb = new StringBuilder();
            foreach (GanjiImage mi in SendPicResult)
            {
                sb.Append(mi.image + "|");

            }
            if (sb.ToString().IndexOf('|') > 0)
            {
                sb.Remove(sb.ToString().LastIndexOf('|'), 1);
            }
            myPub.Pic = sb.ToString();
            string czout = myPub.doreqoutPub2(false, "http://post.58.com/135/8/s5/submit?PGTID=" + myPub.GTID + "&ClickID=1", "");


            label4.Text = myPub.LastStatus;
            richTextBox2.Text += czout;
        }

        private void button12_Click(object sender, EventArgs e)
        {
            ScriptControlClass js = new ScriptControlClass();
            js.Language = "javascript";
            var a1 = js.Eval(" (new Date().getTime() *10).toFixed(0)");
            string a2 = new Random().Next(10316818, 99316818).ToString() + new Random().Next(83893907, 83893907).ToString();

            my58HousePub myPub = new my58HousePub(cklist);
            myPub.GTID = a1.ToString() + "." + a2;
            myPub.doreqoutget(true, "http://post.58.com/135?PGTID=" + myPub.GTID + "&ClickID=6", "");
            myPub.xiaoqu = "338043";
            myPub.xiaoquname = "水岸枫情";
            myPub.localArea = "141";
            myPub.localDiduan = "4900";
            myPub.dizhi = "联丰薛家南路";
            myPub.area = "111";
            myPub.Floor = "1";
            myPub.zonglouceng = "11";
            myPub.MinPrice = "1111";
            myPub.Title = "水岸风情1111出租精装修出售";
            myPub.Content = "水岸风情1111出租精装修出售水岸风情1111出租精装修出售水岸风情1111出租精装修出租水岸风情1111出租精装修出租水岸风情1111出租精装修出租";
            myPub.goblianxiren = "王成";
            myPub.Phone = "15957899036";
            myPub.userid = this.userid;
            myPub.taoneimianji = "111";
            StringBuilder sb = new StringBuilder();
            foreach (GanjiImage mi in SendPicResult)
            {
                sb.Append(mi.image + "|");

            }

            if (sb.ToString().IndexOf('|') > 0)
            {

                sb.Remove(sb.ToString().LastIndexOf('|'), 1);
            }
            myPub.Pic = sb.ToString();
            string czout = myPub.doreqoutPub1(false, "http://post.58.com/135/12/s5/submit?PGTID=" + myPub.GTID + "&ClickID=1", "");
            label4.Text = myPub.LastStatus;
            richTextBox2.Text += czout;
        }
    }
}
